﻿using AuthenticationAPI.Models.DbContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AuthenticationAPI.Models.Utility
{
    public class ReviewProjectHelper
    {

        private static void ApproveProject(int prjId, DateTime date)
        {
            using (var db = new MetroProjectsEntities())
            {
                var prePts = db.PreReviewMonitorPoints.Where(p => p.PrjId == prjId && p.DateTime.Value == date).ToList();
                var pts = (from t in prePts
                           select new MonitorPoint()
                           {
                               DateTime = t.DateTime,
                               Name = t.Name,
                               PrjId = prjId,
                               Value = t.Value
                           }).ToList();
                var exsitedNames = pts.Select(p => p.Name).ToList();
                var exsitedPts = from p in db.MonitorPoints
                                 where p.PrjId == prjId &&
                                     p.DateTime.Value == date && exsitedNames.Contains(p.Name)
                                 select p;

                db.PreReviewMonitorPoints.RemoveRange(prePts);
                db.MonitorPoints.RemoveRange(exsitedPts);
                db.MonitorPoints.AddRange(pts);

                var summaryPreviewList = (from p in db.PointsSummaryNeedToBeRevieweds
                                          where p.PrjId == prjId && p.DateTime == date
                                          select p).ToList();
                db.PointsSummaryNeedToBeRevieweds.RemoveRange(summaryPreviewList);


                db.SaveChanges();
            }
        }

        private static void DenyProject(int prjId, DateTime date)
        {
            using (var db = new MetroProjectsEntities())
            {
                var prePts = db.PreReviewMonitorPoints.Where(p => p.PrjId == prjId && p.DateTime.Value == date).ToList();

                var summaryPreviewList = (from p in db.PointsSummaryNeedToBeRevieweds
                                          where p.PrjId == prjId && p.DateTime == date
                                          select p).ToList();
                db.PreReviewMonitorPoints.RemoveRange(prePts);
                db.PointsSummaryNeedToBeRevieweds.RemoveRange(summaryPreviewList);
                db.SaveChanges();
            }
        }

        /// <summary>
        /// 执行审核一个项目的操作
        /// </summary>
        /// <param name="prjId">工程id</param>
        /// <param name="date">日期</param>
        /// <param name="action">通过还是不通过,1为通过,0为不通过</param>
        public static void ReviewProject(int prjId, DateTime date, int action)
        {
            if (action == 1)
            {
                ReviewProjectHelper.ApproveProject(prjId, date);
            }
            else
            {
                ReviewProjectHelper.DenyProject(prjId, date);
            }
        }
    }
}